//
//  NetWorkOperation.m
//  sp
//
//  Created by 陶秋安 on 16/2/19.
//  Copyright © 2016年 孙智慧. All rights reserved.
//

#import "NetWorkOperation.h"

@implementation NetWorkOperation

- (id)initWithDelegate:(id<FxOperationDelegate>)delegate

{
    self = [super init];
    
    if (self) {
        
        _delegate = delegate;
        
    }
    
    return self;
}

-(void) setOpInfo:(NSDictionary *)opInfo
{
    
    _opInfo=opInfo;
    
}

#pragma mark 下载
-(void) down
{
    NSURL *URL = [NSURL URLWithString:[_opInfo objectForKey:@"url" ]];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request
                                                            completionHandler:
                                              ^(NSURL *location, NSURLResponse *response, NSError *error)
                                              {
                                                  
                                                  // 输出下载文件原来的存放目录
                                                  NSLog(@"location:--%@", location);
                                           
                                                  [self exSuccForDownLoad:location andFlag:[_opInfo objectForKey:@"flag" ]];
                                                  
                                              }];
    
    [downloadTask resume];
}

-(void) get:(NSInteger)flag;
{
    
    //GET请求, 也可以给服务器发送信息, 也有参数(微博用户名,用户id)
    //1.构造URL, 参数直接拼接在url连接后
    //NSURL *url = [NSURL URLWithString:[_opInfo objectForKey:@"url" ]];
    NSURL *url= [[NSURL alloc] initWithString:[[_opInfo objectForKey:@"url"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    //2.构造Request
    //把get请求的请求头保存在request里
    //NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 参数
    // (1)url
    // (2)缓存策略
    // (3)超时的时间, 经过120秒之后就放弃这次请求
    //NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:120];
    //NSURLRequest 不可变,不能动态的添加请求头信息
    
    //可变的对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //(1)设置请求方式
    [request setHTTPMethod:@"GET"];
    
    //(2)超时时间
    [request setTimeoutInterval:60];
    
    //(3)缓存策略
    //[request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
    
    //(4)设置请求头其他内容
    //[request setValue:<#(NSString *)#> forHTTPHeaderField:<#(NSString *)#>];
    //[request addValue:<#(NSString *)#> forHTTPHeaderField:<#(NSString *)#>];
    //[request setAllHTTPHeaderFields:<#(NSDictionary *)#>];
    
    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"]; //告诉服务,返回的数据需要压缩
    
    
    //3.构造Session
    NSURLSession *session = [NSURLSession sharedSession];
    
    //4.构造要执行的任务task
    /**
     * task
     *
     * @param data 返回的数据
     * @param response 响应头
     * @param error 错误信息
     *
     */
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        if (error == nil) {
            
            [self exSuccForGet:data andFlag:flag];
        }
    }];
    
    //5.
    [task resume];
    
}
- (void) post
{
    
    //1.构造URL
    NSURL *url = [NSURL URLWithString:[_opInfo objectForKey:@"url" ]];
    
    //2.构造Request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //(1)设置为POST请求
    [request setHTTPMethod:@"POST"];
    
    
    //(2)超时
    [request setTimeoutInterval:60];
    
    //(3)设置请求头
    //[request setAllHTTPHeaderFields:nil];
    
    //(4)设置请求体
    //发新浪微博
    //请求体里需要包含至少两个参数
    //指定用户的令牌 微博正文
    //access_token status
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSString *bodyStr = [_opInfo objectForKey:@"body" ] ;
    
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    
    //设置请求体
    [request setHTTPBody:bodyData];
    
    //3.构造Session
    NSURLSession *session = [NSURLSession sharedSession];
    
    //4.task
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        [self exSuccForPost:data];
    }];
    
    //5.
    [task resume];
}
-(void) exSuccForDownLoad:(id)location andFlag:(NSString *) flag
{
    [_delegate opSuccessForDownLoad:location andFlag:flag];
}
-(void) exSuccForGet:(id)data andFlag:(NSInteger) flag
{
    [_delegate opSuccessForGet:data andFlag:flag];
}
-(void) exSuccForPost:(id)data
{
    [_delegate opSuccessForPost:data];
}
-(void) exSuccForGet:(id)data
{}
@end
